using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace IMServer.Models.Message
{
    [BsonDiscriminator(RootClass = true)]
    [BsonKnownTypes(typeof(ChatMessage))]
    [BsonKnownTypes(typeof(GroupChatMessage))]
    public abstract class BaseMessage
    {
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("messageId")] 
        public string MessageId { get; set; } = null!;

        [BsonElement("senderId")]
        public string SenderId { get; set; } = null!;

        [BsonElement("senderName")]
        public string SenderName { get; set; } = null!;

        [BsonElement("senderAvatar")]
        public string SenderAvatar { get; set; } = null!;

        [BsonElement("receiverId")]
        public string ReceiverId { get; set; } = null!;

        [BsonElement("content")]
        public string Content { get; set; } = null!;

        [BsonElement("IsRead")]
        public bool IsRead { get; set; } = false;

        [BsonElement("messageType")]
        public abstract string MessageType { get; set; }

        [BsonElement("timestamp")]
        [BsonRepresentation(BsonType.DateTime)]
        public DateTime Timestamp { get; set; } = DateTime.UtcNow;

        public virtual string ToJson()
        {
            var messageData = new
            {
                MessageId,
                SenderId,
                SenderName,
                SenderAvatar,
                ReceiverId,
                Content,
                MessageType,
                Timestamp,
                IsRead
            };
            return System.Text.Json.JsonSerializer.Serialize(messageData);
        }
        
        public BaseMessage()
        {
            GenerateMessageId();
        }
        
        public void GenerateMessageId()
        {
            MessageId = Guid.NewGuid().ToString();
        }
    }
}